<!-- 房间列表 -->
<template>
  <div class="wrapper">

    <a-card :body-style="{ padding: 0 }" :bordered="false">
      <a-row :gutter="24">
        <a-col :md="6" :sm="24">
          <a-card hoverable style="height:600px;overflow-y:auto">
            <a-tree :showLine="true" @expand="onExpand" :expandedKeys="expandedKeys" :autoExpandParent="autoExpandParent" v-model="checkedKeys" @select="onSelect" :selectedKeys="selectedKeys" :treeData="treeData" :replaceFields="replaceFields" />
          </a-card>
        </a-col>
        <a-col :md="18" :sm="24">
          <search-form ref="searchFrom" :area="'meter'" @search="search" :addType="0">
          </search-form>
          <a-spin :indicator="indicator" :spinning="spinning" tip="获取数据中...">
            <div class="spin-content">
              <div>
                <a-button type="primary" @click="SetUser">
                  批量设置抄表人
                </a-button>
                <a-popconfirm  @confirm="DelUser" placement="left" title="确定删除?" okText="确定" cancelText="取消">
                <a-button  type="danger" style="margin-left: 20px;">
                  批量删除抄表人
                </a-button>
                </a-popconfirm>
              </div>
              <a-table size="small" bordered :rowKey="(record) => record.id" :columns="columns" :dataSource="tableList" :pagination="pagination" :rowSelection="{
      selectedRowKeys: selectedRowKeys,
      onChange: onSelectChange,
    }">
                <!-- <span slot="action" slot-scope="text, record">
                  <template>
                    <a size="small" type="link" @click="handleEdit(record)">编辑</a>
                    <a-divider type="vertical" />
                    <a size="small" type="link" @click="handleView(record)">查看</a>
                  </template>
                </span> -->
              </a-table>
            </div>
          </a-spin>
        </a-col>
      </a-row>
    </a-card>

    <a-modal title="设置抄表人" :width="400" :maskClosable="false" :visible="visibleMeter" @cancel="visibleMeter = false">
      <a slot="footer">
        <a-button @click="visibleMeter = false">取消</a-button>
        <a-button type="primary" @click="handleSave">确定</a-button>

      </a>
      <div>
        <a-form :form="form">
          <a-form-item v-bind="formItemLayout1" label="选择抄表人">
            <a-select showSearch optionFilterProp="children" v-model="form.meterUser">
              <a-select-option v-for="(item, index) in meterUserList" :key="item.value" :value="item.value">{{
        item.label }}</a-select-option>
            </a-select>

          </a-form-item>

        </a-form>
      </div>

    </a-modal>

  </div>
</template>

<script>
import {
  getUserRoomList,
  getBuildingTree,
  getModalUserList,
  saveUserRooms,
  deleteUserRoomIds
} from "@/api/allApi";
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import '@/views/treeselect1.css'
import SearchForm from "./modules/searchform";
const columns = [
  {
    title: "小区名",
    dataIndex: "ResidentialAreaName",
    key: "ResidentialAreaName",
    align: "center",
  },
  {
    title: "楼幢名",
    dataIndex: "BuildingName",
    key: "BuildingName",
    align: "center",
  },
  {
    title: "房间名",
    dataIndex: "RoomName",
    key: "RoomName",
    align: "center",
  },
  {
    title: "表类型",
    dataIndex: "MeterTypeName",
    key: "MeterTypeName",
    align: "center",
  },
  {
    title: "抄表人",
    dataIndex: "UserTrueName",
    key: "UserTrueName",
    align: "center",
  },

  {
    title: "设置日期",
    dataIndex: "SetTime",
    key: "SetTime",
    align: "center",
  },

];
export default {
  name: "",
  components: { SearchForm, Treeselect },
  props: [],
  data () {
    return {
      columns: columns,
      action: "add",
      indicator: <a-icon type="loading" style="font-size: 24px" spin />,
      spinning: false,
      tableList: [],
      residentialAreaID: '',
      queryParam: {
        index: 1,
        pageSize: 10,
        buildingID: '',
        MeterType:1

      },
      form: {
        meterUser: undefined
      },
      formItemLayout1: {
        labelCol: {
          xs: { span: 8 },
          sm: { span: 8 }
        },
        wrapperCol: {
          xs: { span: 16 },
          sm: { span: 16 }
        }
      },
      meterUserList: [],
      visibleMeter: false,
      autoExpandParent: true,
      expandedKeys: [],

      checkedKeys: [],
      selectedKeys: [],
      treeData: [],
      replaceFields: {
        children: 'Childrens', title: 'name', key: 'id'
      },
      selectedRows: [],
      selectedRowKeys: [],
      pagination: {
        onChange: (index, pageSize) => {
          this.pageOnChange(index, pageSize);
        },
        current: 1,
        total: 0,
        showQuickJumper: true,
        size: "small",
        defaultPageSize: 10,
        showTotal: (total) => `共 ${total} 条数据`,
        showSizeChanger: true,
        pageSizeOptions: ["5", "10", "15", "20","50","100"],
        onShowSizeChange: (index, pageSize) => {
          this.pageOnChange(index, pageSize);
        },
        position: "bottom",
      },
    };
  },
  computed: {},
  watch: {},
  created () {

    getBuildingTree().then(res => {
      console.log(res)
      this.treeData = res.data
    })

    getModalUserList({ index: 1, pageSize:50, roleID: 54 }).then(res => {
      console.log(res)
      this.meterUserList = res.data.map(item => {
        return {
          label: item.TrueName,
          value: item.id,
        }
      })
    })
  },
  mounted () {
    this.initData(this.queryParam)
  },
  methods: {
    async initData (params) {
      this.spinning = true;

      const { data, message, page } = await getUserRoomList({ ...params, residentialAreaID: this.residentialAreaID });
      this.pagination.total = page.RecordCount;
      this.tableList = data;
      this.tableList.map((a) => {
        a.addTime = this.$moment(a.addTime).format('YYYY-MM-DD HH:mm:ss');
        // a.isExamine = a.isExamine === true ? "是" : "否";
        // a.isComplete = a.confirmUserID > 0 ? "是" : "否";
      });
      this.spinning = false;
    },

    search (data) {
      Object.assign(this.queryParam, data, { index: 1 });
      this.pagination.current = 1;
      this.initData(this.queryParam);
    },

    /** 选择框 */
    onSelectChange (selectedRowKeys, selectedRow) {
      console.log('selectedRowKeys changed: ', selectedRow)

      this.selectedRows = selectedRow;
      this.selectedRowKeys = selectedRowKeys;
    },
    // 添加
    handleAdd () {
      this.action = "add";
      // residentialAreaID: '',
      //   buildingID: '',
      if (!this.residentialAreaID && !this.queryParam.buildingID) {
        this.$message.info('先选择小区和楼栋')
        return
      }
      this.$refs.infomodal.view();
    },
    SetUser () {
      if (this.selectedRows && this.selectedRows.length > 0) {
        this.visibleMeter = true
      } else {
        this.$message.info('请选择操作数据')
        return
      }

    },
    DelUser () {
      if (this.$refs.searchFrom && this.$refs.searchFrom.queryParam.meterUser>0) {
        let meterUserID = this.$refs.searchFrom.queryParam.meterUser
        console.log('meterUserID',meterUserID) 
        deleteUserRoomIds({ RoomIDs: this.selectedRowKeys, MeterType: this.queryParam.MeterType,MeterUserID: meterUserID}).then(res => {
          this.initData(this.queryParam)
          this.visibleMeter = false
          this.selectedRowKeys = []
        })
      }
      else
      {
        this.$message.error('请选择抄表人')
      }
    },

    handleSave () {
      let _this = this
      if (!_this.form.meterUser) {
        _this.$message.error('请选择抄表人')
        return
      }
      console.log('_this.queryParam.MeterType',_this.queryParam);
      let p = _this.selectedRows.map(el => {
        return {
          userID: _this.form.meterUser,
          residentialAreaID: el.residentialAreaID,
          buildingID: el.buildingID,
          roomID: el.id,
          meterType: _this.queryParam.MeterType
        }
        
      })
      
      saveUserRooms(p).then(res => {
        if (res.success) {
          _this.initData(_this.queryParam)
          _this.selectedRows = [];
          _this.selectedRowKeys = [];
          _this.visibleMeter = false
        }
      })
    },

    onExpand (expandedKeys) {
      console.log('onExpand', expandedKeys)
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },



    onCheck (checkedKeys) {
      console.log('onCheck', checkedKeys)
      this.checkedKeys = checkedKeys
    },
    onSelect (selectedKeys, e) {
      console.log('onSelect', e.selectedNodes[0])
      if (e.selectedNodes[0].data.props.parentId) {
        this.residentialAreaID = e.selectedNodes[0].data.props.parentId
        this.queryParam.buildingID = e.selectedNodes[0].data.props.id
      } else {
        this.residentialAreaID = e.selectedNodes[0].data.props.id

      }
      this.selectedKeys = selectedKeys
      this.ParentId = selectedKeys[0]
      this.initData(this.queryParam)
    },
    pageOnChange (index, pageSize) {
      this.spinning = true;
      Object.assign(this.pagination, {
        current: index,
        pageSize,
        index,
      });
      Object.assign(this.queryParam, {
        pageSize,
        index,
      });
      this.initData(this.queryParam);
    },
  },
};
</script>
<style>
/** lang='less' scoped */
</style>